package game

import (
	"errors"
	"fmt"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/game"
	"gorm.io/gorm"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateApi
//@description: 新增基础api
//@param: api model.SysApi
//@return: err error

type ProjectService struct{}

var ProjectServiceApp = new(ProjectService)

func (service *ProjectService) CreateProject(param game.BsProject) (err error) {
	return global.GVA_DB.Create(&param).Error
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteApi
//@description: 删除基础api
//@param: api model.SysApi
//@return: err error

func (service *ProjectService) DeleteProject(param game.BsProject) (err error) {
	var entity game.BsProject
	err = global.GVA_DB.First(&entity, "id = ?", param.Id).Error // 根据id查询api记录
	if errors.Is(err, gorm.ErrRecordNotFound) {                  // api记录不存在
		return err
	}
	err = global.GVA_DB.Delete(&entity).Error
	if err != nil {
		return err
	}
	return nil
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetAPIInfoList
//@description: 分页获取数据,
//@param: api model.SysApi, info request.PageInfo, order string, desc bool
//@return: list interface{}, total int64, err error

func (service *ProjectService) GetProjectList(param game.BsProject, info request.PageInfo, order string, desc bool) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&game.BsProject{})
	var pList []game.BsProject

	if param.Title != "" {
		db = db.Where("title LIKE ?", "%"+param.Title+"%")
	}

	err = db.Count(&total).Error

	if err != nil {
		return pList, total, err
	}

	db = db.Limit(limit).Offset(offset)
	OrderStr := "id desc"
	if order != "" {
		orderMap := make(map[string]bool, 5)
		orderMap["id"] = true
		orderMap["update_time"] = true
		orderMap["create_time"] = true
		if !orderMap[order] {
			err = fmt.Errorf("非法的排序字段: %v", order)
			return pList, total, err
		}
		OrderStr = order
		if desc {
			OrderStr = order + " desc"
		}
	}
	err = db.Order(OrderStr).Find(&pList).Error
	return pList, total, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetApiById
//@description: 根据id获取api
//@param: id float64
//@return: api model.SysApi, err error

func (service *ProjectService) GetProjectById(id int) (res game.BsProject, err error) {
	err = global.GVA_DB.First(&res, "id = ?", id).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateApi
//@description: 根据id更新api
//@param: api model.SysApi
//@return: err error

func (service *ProjectService) UpdateProject(p game.BsProject) (err error) {
	return global.GVA_DB.Save(&p).Error
}
